package com.ithaohao.service.Impl;

import com.ithaohao.mapper.InvitationsMapper;
import com.ithaohao.pojo.Application;
import com.ithaohao.pojo.Invitations;
import com.ithaohao.pojo.Result;
import com.ithaohao.service.InvitationsService;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.time.LocalDate;
import java.util.List;

@Service
public class InvitationsServiceImpl implements InvitationsService {

    @Autowired
    private InvitationsMapper invitationsMapper;
    /* 用户已登录
      发布邀请函*/
    @Override
    public Result post(Invitations invitations, HttpSession session) {
        if (session.getAttribute("user") == null) {
            return Result.error("用户未登录，请先登录");
        }
        invitationsMapper.post(invitations);
        return Result.success("发布成功");
    }

    /* 用户已登录
       查看邀请函*/
    @Override
    public Result list(HttpSession session) {
        if (session.getAttribute("user") == null) {
            return Result.error("用户未登录，请先登录");
        }
        List<Application> applicationlist =invitationsMapper.applicationlist();
        return Result.success(applicationlist);
    }

    /* 未登录
       查看邀请函*/
    @Override
    public List<Invitations> selectById(Integer id) {
        return invitationsMapper.selectById(id);
    }
    @Override
    public boolean userExists(String user) {
        return invitationsMapper.userExists(user) > 0;
    }

    @Override
    public boolean DateExists(LocalDate createDate) {
        return invitationsMapper.DateExists(createDate) > 0;
    }

    @Override
    public Result checkAndAdd(Application application, HttpSession session) {
        if (session.getAttribute("user") == null) {
            return Result.error("用户未登录，请先登录");
        }
        if (userExists(application.getUser())) {
            return Result.error("报名失败：用户名已存在");
        }
        if (DateExists(application.getCreateDate())){
            return Result.error("报名失败：报名已截至");
        }
        if (application.getPercent().equals("100%")) {
            return Result.error("报名失败：报名人数已满");
        }
        invitationsMapper.add(application);
        return Result.success();
    }

}
